<template>
  <div class="login-page">
    <div class="top-bar">
      <el-icon class="logo-icon">
        <Notebook />
      </el-icon>
      <div class="logo-text">在线学习平台</div>
    </div>

    <div class="main-content">
      <img class="side-image" :src="loginBg" alt="Login Background" />

      <el-card class="auth-card">
        <div class="card-icon">
          <el-icon><UserFilled /></el-icon>
        </div>

        <el-form v-if="!showRegister" :model="loginForm" :rules="loginRules" ref="loginForm">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              :type="passwordVisible ? 'text' : 'password'" 
              placeholder="密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
              <template #suffix>
                <el-icon @click="togglePasswordVisibility" style="cursor: pointer;">
                  <View v-if="!passwordVisible" />
                  <Hide v-else />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="captcha">
            <el-input v-model="loginForm.captcha" placeholder="验证码">
              <template #prefix>
                <el-icon><Tickets /></el-icon>
              </template>
            </el-input>
            <span class="captcha-code">{{ captchaCode }}</span>
            <el-button @click="generateCaptcha" class="refresh-captcha">刷新验证码</el-button>
          </el-form-item>

          <el-form-item class="form-buttons">
            <el-button type="primary" @click="login">登录</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>

          <div class="error-message" v-if="errorMessage">{{ errorMessage }}</div> <!-- 显示错误消息 -->

          <div class="test-accounts">
            <span>测试账号：</span>
            <el-button class="test-button" @click="loginAsStudent">学生账号</el-button>
            <el-button class="test-button" @click="loginAsAdmin">管理员账号</el-button>
          </div>

          <div class="register-link">
            <span @click="toggleRegister">还没有账户？去注册 →</span>
          </div>
        </el-form>

        <el-form v-else :model="registerForm" :rules="registerRules" ref="registerForm">
          <el-form-item prop="email">
            <el-input v-model="registerForm.email" placeholder="邮箱">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="repeatPassword">
            <el-input v-model="registerForm.repeatPassword" type="password" placeholder="重复输入密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="register" style="width: 350px;">注册</el-button>
          </el-form-item>
          <div class="login-link">
            <span @click="toggleRegister">已有账户？去登录 ←</span>
          </div>
        </el-form>
      </el-card>
    </div>

    <div class="bottom-bar">
      © 版权信息
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import logo from '../assets/logo.png';
import loginBg from '../assets/Login_bg.jpg';
import { User, Lock, Tickets, UserFilled, Message, Notebook } from '@element-plus/icons-vue';
import { View, Hide } from '@element-plus/icons-vue';

export default {
  components: {
    User,
    Lock,
    Tickets,
    UserFilled,
    Message,
    Notebook,
    View,
    Hide
  },
  data() {
    return {
      logo,
      loginBg,
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      registerForm: {
        email: '',
        username: '',
        password: '',
        repeatPassword: ''
      },
      showRegister: false,
      passwordVisible: false,
      captchaCode: '',
      isTestAccount: false,
      errorMessage: '', // 用于存储错误信息
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 11, message: '用户名长度在5到11位之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 11, message: '密码长度在6到11位之间', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.isTestAccount) {
                callback();
              } else if (value !== this.captchaCode) {
                callback(new Error('验证码错误'));
              } else {
                callback();
              }
            }
          }
        ]
      },
      registerRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 11, message: '用户名长度在5到11位之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 11, message: '密码长度在6到11位之间', trigger: 'blur' }
        ],
        repeatPassword: [
          { required: true, message: '请确认密码', trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value !== this.registerForm.password) {
                callback(new Error('两次密码输入不一致'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },
  mounted() {
    this.generateCaptcha();
  },
  methods: {
    togglePasswordVisibility() {
      this.passwordVisible = !this.passwordVisible;
    },
    async login() {
      this.errorMessage = ''; // 清空错误信息
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('/api/login', this.loginForm);
            const { success, token, role, userId, message } = response.data;

            if (success) {
              localStorage.setItem('token', token);
              localStorage.setItem('role', role);
              localStorage.setItem('userId', userId);
              this.$message.success('登录成功');
              if (role === 'admin') {
                this.$router.push('/admin'); 
              } else if (role === 'user') {
                this.$router.push('/user/home'); 
              }
            } else {
              this.errorMessage = message || '登录失败'; // 输出具体的错误信息
            }
          } catch (error) {
            console.error(error);
            this.errorMessage = '登录请求失败';
          } finally {
            this.resetForm();
          }
        }
      });
    },
    async register() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('/api/register', this.registerForm);
            const { success, message } = response.data;

            if (success) {
              this.$message.success('注册成功，转到登录界面');
              this.loginForm.username = this.registerForm.username; 
              this.toggleRegister(); 
              this.resetForm(); 
              this.$router.push(''); 
            } else {
              this.$message.error(`注册失败: ${message}`);
            }
          } catch (error) {
            console.error(error);
            this.$message.error('注册请求失败');
          }
        }
      });
    },
    toggleRegister() {
      this.showRegister = !this.showRegister;
    },
    generateCaptcha() {
      this.captchaCode = Math.random().toString(36).substring(2, 6).toUpperCase();
    },
    resetForm() {
      if (this.showRegister && this.$refs.registerForm) {
        this.$refs.registerForm.resetFields();
      } else if (!this.showRegister && this.$refs.loginForm) {
        this.$refs.loginForm.resetFields();
      }
    },
    loginAsStudent() {
      this.isTestAccount = true;
      this.loginForm.username = 'student';
      this.loginForm.password = 'student123';
      this.login();
    },
    loginAsAdmin() {
      this.isTestAccount = true;
      this.loginForm.username = 'admin';
      this.loginForm.password = 'admin123';
      this.login();
    }
  },
};
</script>

<style lang="scss" scoped>
@use '../assets/scss/LoginPage' as *;
.error-message {
  color: red; /* 错误消息字体颜色 */
  margin-top: 10px; /* 顶部间距 */
}
</style>
